const customerDao = require('../../dao/customerDao.js');
const  winston = require('../../utils/winstonLogger.js');
const fs = require("fs");
module.exports = {
    login : login,
    register : register,
    updateInfo : updateInfo,
    findCustomerById : findCustomerById
}

function login(req,res,next){
    let body = req.body;
    customerDao.login({username:body.username,password:body.password},(err,result)=>{
        if(err){
            winston.error(err);
        }else{
            res.json(result);
        }
    });
}


function register(req,res,next){
    let body = req.body;
    console.log("asdddd.........................................")
    console.log(body);
    let customer = {};
    let  addresses = [];
    let address = {};
    customer.username = body.username;
    customer.password = body.password;
    address.address = body.address;
    address.phone = body.phone;
    address.receiver = body.receiver;
    addresses.push(address);
    customer.addresses = addresses;
    let files = req.files;
    let localPath = 'D:/o2o/images';
    let remotePath = 'http://10.222.29.165:3456/images';
    let customerPath = '/customer/' + body.username + '-' + Date.now() + '.jpg';

    fs.writeFile(localPath + customerPath, files.portrait[0].buffer, function (err) {
        if (err)
            console.error(err);
    });
    customer.portrait = remotePath + customerPath;

    customerDao.register(customer,(err,result)=>{
        if(err){
            winston.error(err);
        }else{

            res.json(result);
        }
    });
}
function updateInfo(req,res,next){
    let body = req.body;
    // let address = {};
    // address.address = body.address;
    // addrsss.phone = body.phone
    let address = {
           address:body.address,
           phone:body.phone,
           receiver:body.name
       }
    customerDao.findCustomerById(body._id,(err,result)=>{
        result.addresses.push(address);
        console.log(result + "=======>");
        customerDao.updateInfo(result,(err,result)=>{
        if(err) winston.error(err);
        else res.json(result);
    });
    });
}

function findCustomerById(req,res,next){
    let customerId = req.params.customerId;
    customerDao.findCustomerById(customerId,(err,result)=>{
        if(err) winston.error(err);
        else res.json(result.addresses);
    });
}